import java.sql.*;

/**
 * JdbcLj连接数据库
 */
public class JdbcLj {
    private String url = "jdbc:mysql://localhost:3306/store";
    private String name = "root";
    private String password = "";
    private Connection connection;


    public Connection getConnection() throws SQLException, ClassNotFoundException {
        if (connection == null || connection.isClosed()) {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(url, name, password);
        }
        return connection;
    }


    public void close() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
            connection = null;
        }
    }

    public int executeUpdate(String sql, Object... values) throws SQLException, ClassNotFoundException {
        // 获取连接
        getConnection();
        // 获取执行sql的对象
        PreparedStatement statement = connection.prepareStatement(sql);
        // 替换占位符
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                statement.setObject(i + 1, values[0]);
            }
        }
        // 执行sql
        int rows = statement.executeUpdate();
        // 返回
        return rows;
    }

    public ResultSet executeQuery(String sql, Object... values) throws SQLException, ClassNotFoundException {
        getConnection();
        PreparedStatement statement = connection.prepareStatement(sql);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                statement.setObject(i + 1, values[0]);
            }
        }
        ResultSet resultSet = statement.executeQuery();
        return resultSet;
    }


}
